import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/unified_config.dart';

class BuildMonitorPage extends StatefulWidget {
  final UnifiedConfig config;

  const BuildMonitorPage({super.key, required this.config});

  @override
  State<BuildMonitorPage> createState() => _BuildMonitorPageState();
}

class _BuildMonitorPageState extends State<BuildMonitorPage>
    with TickerProviderStateMixin {
  // 构建状态
  bool _isBuilding = false;
  double _buildProgress = 0.0;
  String _currentStep = '准备构建...';
  String _buildResult = '';
  Duration _buildDuration = Duration.zero;
  DateTime? _buildStartTime;

  // 日志相关
  final List<String> _buildLogs = [];
  final ScrollController _logScrollController = ScrollController();

  // 动画控制器
  late AnimationController _progressAnimationController;
  late AnimationController _pulseAnimationController;
  late Animation<double> _progressAnimation;
  late Animation<double> _pulseAnimation;

  // 计时器
  Timer? _durationTimer;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    _progressAnimationController.dispose();
    _pulseAnimationController.dispose();
    _durationTimer?.cancel();
    _logScrollController.dispose();
    super.dispose();
  }

  void _initAnimations() {
    _progressAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _pulseAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _progressAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _progressAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    _pulseAnimation = Tween<double>(begin: 0.8, end: 1.2).animate(
      CurvedAnimation(
        parent: _pulseAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    _pulseAnimationController.repeat(reverse: true);
  }

  Future<void> _startBuild() async {
    if (_isBuilding) return;

    setState(() {
      _isBuilding = true;
      _buildProgress = 0.0;
      _currentStep = '开始构建...';
      _buildResult = '';
      _buildLogs.clear();
      _buildStartTime = DateTime.now();
    });

    _progressAnimationController.forward();
    _startDurationTimer();

    try {
      final command = widget.config.generateCommand();
      _addLog('🚀 开始执行构建命令');
      _addLog('📋 命令: $command');

      await _executeNuitkaBuild(command);
    } catch (e) {
      _addLog('❌ 构建过程中发生错误: $e');
      setState(() {
        _buildResult = 'error';
        _currentStep = '构建失败';
      });
    } finally {
      _stopBuild();
    }
  }

  Future<void> _executeNuitkaBuild(String command) async {
    try {
      _updateBuildProgress('解析构建命令...', 0.1);

      // 解析命令 - 更智能地处理包含空格的路径
      List<String> parts = [];
      bool inQuotes = false;
      String currentPart = '';

      for (int i = 0; i < command.length; i++) {
        final char = command[i];
        if (char == '"') {
          inQuotes = !inQuotes;
        } else if (char == ' ' && !inQuotes) {
          if (currentPart.isNotEmpty) {
            parts.add(currentPart);
            currentPart = '';
          }
        } else {
          currentPart += char;
        }
      }
      if (currentPart.isNotEmpty) {
        parts.add(currentPart);
      }

      if (parts.isEmpty) {
        throw Exception('无效的构建命令');
      }

      // 使用 python -m nuitka 而不是直接调用 nuitka
      String executable;
      List<String> arguments;

      if (parts[0] == 'nuitka') {
        executable = 'python';
        arguments = ['-m', 'nuitka', ...parts.sublist(1)];
      } else {
        executable = parts[0];
        arguments = parts.sublist(1);
      }

      _addLog('🔧 执行程序: $executable');
      _addLog('📝 参数: ${arguments.join(' ')}');

      _updateBuildProgress('启动构建进程...', 0.2);

      // 启动进程
      final process = await Process.start(
        executable,
        arguments,
        workingDirectory: Directory.current.path,
      );

      _addLog('✅ 构建进程已启动');
      _updateBuildProgress('正在构建...', 0.3);

      // 监听标准输出
      process.stdout.transform(utf8.decoder).listen((data) {
        final lines = data.split('\n');
        for (final line in lines) {
          if (line.trim().isNotEmpty) {
            _addLog('STDOUT: $line');
            _updateBuildProgressFromOutput(line);
          }
        }
      });

      // 监听错误输出
      process.stderr.transform(utf8.decoder).listen((data) {
        final lines = data.split('\n');
        for (final line in lines) {
          if (line.trim().isNotEmpty) {
            _addLog('STDERR: $line');
          }
        }
      });

      // 等待进程完成
      final exitCode = await process.exitCode;

      if (exitCode == 0) {
        _addLog('✅ 构建成功完成!');
        _updateBuildProgress('构建完成', 1.0);
        setState(() {
          _buildResult = 'success';
          _currentStep = '构建成功';
        });
      } else {
        _addLog('❌ 构建失败，退出代码: $exitCode');
        setState(() {
          _buildResult = 'error';
          _currentStep = '构建失败';
        });
      }
    } catch (e) {
      _addLog('❌ 执行错误: $e');
      setState(() {
        _buildResult = 'error';
        _currentStep = '执行错误';
      });
    }
  }

  void _updateBuildProgressFromOutput(String output) {
    // 根据输出内容更新进度
    if (output.contains('Nuitka-Options')) {
      _updateBuildProgress('解析选项...', 0.4);
    } else if (output.contains('Nuitka-Plugins')) {
      _updateBuildProgress('加载插件...', 0.5);
    } else if (output.contains('Nuitka:INFO')) {
      _updateBuildProgress('编译中...', 0.6);
    } else if (output.contains('Nuitka:WARNING')) {
      _updateBuildProgress('处理警告...', 0.7);
    } else if (output.contains('Nuitka:ERROR')) {
      _updateBuildProgress('处理错误...', 0.8);
    } else if (output.contains('Successfully created')) {
      _updateBuildProgress('生成可执行文件...', 0.9);
    }
  }

  void _updateBuildProgress(String step, double progress) {
    setState(() {
      _currentStep = step;
      _buildProgress = progress;
    });
  }

  void _addLog(String message) {
    setState(() {
      final timestamp = DateTime.now().toString().substring(11, 19);
      _buildLogs.add('[$timestamp] $message');
    });

    // 自动滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_logScrollController.hasClients) {
        _logScrollController.animateTo(
          _logScrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _startDurationTimer() {
    _durationTimer?.cancel();
    _durationTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_buildStartTime != null) {
        setState(() {
          _buildDuration = DateTime.now().difference(_buildStartTime!);
        });
      }
    });
  }

  void _stopBuild() {
    setState(() {
      _isBuilding = false;
    });

    _durationTimer?.cancel();
    _progressAnimationController.reset();

    _addLog('🏁 构建过程结束');
  }

  void _clearLogs() {
    setState(() {
      _buildLogs.clear();
    });
  }

  void _copyAllLogs() async {
    if (_buildLogs.isEmpty) return;

    final allLogs = _buildLogs.join('\n');
    await Clipboard.setData(ClipboardData(text: allLogs));

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('所有日志已复制到剪贴板'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('构建监控'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.clear_all),
            onPressed: _buildLogs.isNotEmpty ? _clearLogs : null,
            tooltip: '清空日志',
          ),
        ],
      ),
      body: Column(
        children: [
          // 构建状态卡片
          _buildStatusCard(),

          // 进度指示器
          _buildProgressIndicator(),

          // 控制按钮
          _buildControlButtons(),

          // 日志区域
          Expanded(child: _buildLogArea()),
        ],
      ),
    );
  }

  Widget _buildStatusCard() {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  _isBuilding ? Icons.build : Icons.build_outlined,
                  color: _isBuilding
                      ? Theme.of(context).colorScheme.primary
                      : Theme.of(
                          context,
                        ).colorScheme.onSurface.withValues(alpha: 0.6),
                ),
                const SizedBox(width: 8),
                Text('构建状态', style: Theme.of(context).textTheme.titleMedium),
                const Spacer(),
                Text(
                  _formatDuration(_buildDuration),
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Theme.of(
                      context,
                    ).colorScheme.onSurface.withValues(alpha: 0.7),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Text(_currentStep, style: Theme.of(context).textTheme.bodyLarge),
            if (_buildResult.isNotEmpty) ...[
              const SizedBox(height: 8),
              Row(
                children: [
                  Icon(
                    _buildResult == 'success'
                        ? Icons.check_circle
                        : Icons.error,
                    color: _buildResult == 'success'
                        ? Colors.green
                        : Colors.red,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _buildResult == 'success' ? '构建成功' : '构建失败',
                    style: TextStyle(
                      color: _buildResult == 'success'
                          ? Colors.green
                          : Colors.red,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildProgressIndicator() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('进度', style: Theme.of(context).textTheme.bodyMedium),
              Text(
                '${(_buildProgress * 100).toInt()}%',
                style: Theme.of(context).textTheme.bodyMedium,
              ),
            ],
          ),
          const SizedBox(height: 8),
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              return LinearProgressIndicator(
                value: _buildProgress,
                backgroundColor: Theme.of(
                  context,
                ).colorScheme.surfaceContainerHighest,
                valueColor: AlwaysStoppedAnimation<Color>(
                  _isBuilding
                      ? Theme.of(context).colorScheme.primary
                      : _buildResult == 'success'
                      ? Colors.green
                      : _buildResult == 'error'
                      ? Colors.red
                      : Theme.of(context).colorScheme.primary,
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildControlButtons() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            child: AnimatedBuilder(
              animation: _pulseAnimation,
              builder: (context, child) {
                return Transform.scale(
                  scale: _isBuilding ? _pulseAnimation.value : 1.0,
                  child: ElevatedButton.icon(
                    onPressed: !_isBuilding ? _startBuild : null,
                    icon: _isBuilding
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : const Icon(Icons.play_arrow),
                    label: Text(_isBuilding ? '构建中...' : '开始构建'),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(width: 12),
          ElevatedButton.icon(
            onPressed: !_isBuilding ? _clearLogs : null,
            icon: const Icon(Icons.clear),
            label: const Text('清空日志'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLogArea() {
    return Card(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.terminal),
                const SizedBox(width: 8),
                Text('构建日志', style: Theme.of(context).textTheme.titleMedium),
                const Spacer(),
                if (_buildLogs.isNotEmpty) ...[
                  IconButton(
                    icon: const Icon(Icons.copy),
                    onPressed: _copyAllLogs,
                    tooltip: '复制所有日志',
                    iconSize: 20,
                  ),
                  const SizedBox(width: 8),
                ],
                Text(
                  '${_buildLogs.length} 条记录',
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Theme.of(
                      context,
                    ).colorScheme.onSurface.withValues(alpha: 0.6),
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          Expanded(
            child: _buildLogs.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.description_outlined,
                          size: 48,
                          color: Theme.of(
                            context,
                          ).colorScheme.onSurface.withValues(alpha: 0.4),
                        ),
                        const SizedBox(height: 16),
                        Text(
                          '暂无构建日志',
                          style: Theme.of(context).textTheme.bodyLarge
                              ?.copyWith(
                                color: Theme.of(
                                  context,
                                ).colorScheme.onSurface.withValues(alpha: 0.6),
                              ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '点击"开始构建"按钮开始构建过程',
                          style: Theme.of(context).textTheme.bodyMedium
                              ?.copyWith(
                                color: Theme.of(
                                  context,
                                ).colorScheme.onSurface.withValues(alpha: 0.4),
                              ),
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    controller: _logScrollController,
                    padding: const EdgeInsets.all(8),
                    itemCount: _buildLogs.length,
                    itemBuilder: (context, index) {
                      final log = _buildLogs[index];
                      return Padding(
                        padding: const EdgeInsets.symmetric(vertical: 2),
                        child: SelectableText(
                          log,
                          style: TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 12,
                            color: _getLogColor(log),
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Color _getLogColor(String log) {
    if (log.contains('❌') || log.contains('ERROR')) {
      return Colors.red;
    } else if (log.contains('⚠️') || log.contains('WARNING')) {
      return Colors.orange;
    } else if (log.contains('✅') || log.contains('SUCCESS')) {
      return Colors.green;
    } else if (log.contains('🚀') || log.contains('INFO')) {
      return Theme.of(context).colorScheme.primary;
    }
    return Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.8);
  }

  String _formatDuration(Duration duration) {
    final hours = duration.inHours;
    final minutes = duration.inMinutes % 60;
    final seconds = duration.inSeconds % 60;

    if (hours > 0) {
      return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    } else {
      return '$minutes:${seconds.toString().padLeft(2, '0')}';
    }
  }
}
